import React, { Component } from "react";
import { Link, Route, Switch } from "react-router-dom";

class Home extends Component {
  render() {
    return <div>这是home页面</div>;
  }
}
class About extends Component {
  render() {
    return <div>这是about页面</div>;
  }
}
class Detail extends Component {
  render() {
    console.log(this.props);
    // console.log(this.props.location.search);

    // const obj = new URL("http://localhost:3000/detail?id=456&name=lisi");
    // const id = obj.searchParams.get("id");

    const searchParams = new URLSearchParams(this.props.location.search);
    const id = searchParams.get("id");

    return <div>这是detail页面 - {id}</div>;
  }
}

class App extends Component {
  state = {};
  render() {
    return (
      <>
        <h2>动态路由传参</h2>
        <ul>
          <li>
            <Link to="/home">首页</Link>
          </li>
          <li>
            <Link to="/about">关于页</Link>
          </li>
          <li>
            <Link to="/detail?id=123&name=zhangsan">详情页</Link>
          </li>
          <li>
            {/* <Link to="/detail?id=456&name=lisi">详情页</Link> */}
            <Link
              to={{
                pathname: "/detail",
                search: "?id=456&name=lisi",
                hash: "#lkkk",
                // state的传参是在url上面不可见的传参
                // 既美观又安全
                state: {
                  name: "cxk",
                },
              }}
            >
              详情页
            </Link>
          </li>
        </ul>

        <hr />

        <Switch>
          <Route path="/home" component={Home}></Route>
          <Route path="/about" component={About}></Route>
          <Route path="/detail" component={Detail}></Route>
        </Switch>
      </>
    );
  }
}

export default App;
